/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-02-29 19:20:40
 * @Description  : 用户的系统角色权限验证
 */

const { ERROR_SYSTEM_CODE } = require('@/constants/errorCode')
const { getUserPermissionsById } = require('@/controller/userController')
const R = require('@/models/Response')

/**
 *
 * @param {*} auth 权限字符串（ename）
 * @returns
 */
module.exports.verifyAuth = (auth) => {
  return async (ctx, next) => {
    // 获取用户的权限列表，判断是否拥有该权限
    const user = await getUserPermissionsById(ctx.user.id)
    const isPass = user.role.Permissions.some((item) => {
      return auth.includes(item.ename)
    })

    if (!isPass) {
      ctx.body = R.error(ERROR_SYSTEM_CODE.PERMISSION_ERROR)
      return
    }

    await next()
  }
}
